package com.hongqianping.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.hongqianping.entity.BuserTable;
import com.hongqianping.entity.Focustable;
import com.hongqianping.entity.GoodsTable;
import com.hongqianping.entity.GoodsType;
import com.hongqianping.service.FocustableService;
import com.hongqianping.service.GoodsTableService;
import com.hongqianping.service.GoodsTypeService;

import jakarta.servlet.http.HttpSession;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Controller
public class FavoriteController {

    @Autowired
    private FocustableService focustableService;

    @Autowired
    private GoodsTableService goodsTableService;

    @Autowired
    private GoodsTypeService goodsTypeService;

    @PostMapping("/addToFavorites")
    @ResponseBody
    public ResponseEntity<Map<String, Object>> addToFavorites(@RequestParam("goodsId") Integer goodsId, HttpSession session) {
        BuserTable currentUser = (BuserTable) session.getAttribute("currentUser");
        if (currentUser == null) {
            Map<String, Object> response = new HashMap<>();
            response.put("success", false);
            response.put("message", "请先登录！");
            return new ResponseEntity<>(response, HttpStatus.UNAUTHORIZED);
        }

        // 检查商品是否已被用户收藏
        LambdaQueryWrapper<Focustable> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(Focustable::getBusertableId, currentUser.getId())
                    .eq(Focustable::getGoodstableId, goodsId);
        Focustable existingFavorite = focustableService.getOne(queryWrapper);

        Map<String, Object> response = new HashMap<>();
        if (existingFavorite != null) {
            response.put("success", false);
            response.put("message", "该商品已在您的收藏夹中！");
            return new ResponseEntity<>(response, HttpStatus.OK);
        }

        Focustable newFavorite = new Focustable();
        newFavorite.setBusertableId(currentUser.getId());
        newFavorite.setGoodstableId(goodsId);
        newFavorite.setFocustime(LocalDateTime.now());

        boolean saved = focustableService.save(newFavorite);
        if (saved) {
            response.put("success", true);
            response.put("message", "商品收藏成功！");
            return new ResponseEntity<>(response, HttpStatus.OK);
        } else {
            response.put("success", false);
            response.put("message", "商品收藏失败，请稍后再试！");
            return new ResponseEntity<>(response, HttpStatus.INTERNAL_SERVER_ERROR);
        }
    }

    @GetMapping("/favorites")
    public String viewFavorites(HttpSession session, Model model) {
        BuserTable currentUser = (BuserTable) session.getAttribute("currentUser");
        if (currentUser == null) {
            return "redirect:/login.html";
        }

        // 获取导航栏所有商品类型
        List<GoodsType> goodsTypes = goodsTypeService.list();
        model.addAttribute("goodsTypes", goodsTypes);

        LambdaQueryWrapper<Focustable> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(Focustable::getBusertableId, currentUser.getId())
                    .orderByDesc(Focustable::getFocustime);
        List<Focustable> favoriteItems = focustableService.list(queryWrapper);

        List<Map<String, Object>> favoritedGoodsWithId = new ArrayList<>();
        for (Focustable item : favoriteItems) {
            GoodsTable goods = goodsTableService.getById(item.getGoodstableId());
            if (goods != null) {
                Map<String, Object> favoriteEntry = new HashMap<>();
                favoriteEntry.put("focustableId", item.getId()); // 传递Focustable ID
                favoriteEntry.put("goods", goods); // 传递GoodsTable对象
                favoritedGoodsWithId.add(favoriteEntry);
            }
        }

        model.addAttribute("favoritedGoods", favoritedGoodsWithId);
        return "favorites"; // 将视图名称从 "user/favorites" 改为 "favorites"
    }

    @PostMapping("/removeFavorite")
    public String removeFavorite(@RequestParam("favoriteId") Integer favoriteId, HttpSession session, Model model) {
        BuserTable currentUser = (BuserTable) session.getAttribute("currentUser");
        if (currentUser == null) {
            return "redirect:/login.html";
        }

        Focustable favoriteItem = focustableService.getById(favoriteId);
        if (favoriteItem != null && favoriteItem.getBusertableId().equals(currentUser.getId())) {
            focustableService.removeById(favoriteId);
        }
        return "redirect:/favorites";
    }
} 